package com.e1xp.deport_management_system.controller;


import com.e1xp.deport_management_system.entity.Io;
import com.e1xp.deport_management_system.entity.User;
import com.e1xp.deport_management_system.exception.CustomException;
import com.e1xp.deport_management_system.service.IIoService;
import com.e1xp.deport_management_system.utils.AjaxResponse;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author E1xP
 * @since 2021-04-09
 */
@Controller
@RequestMapping("/io")
public class IoController {

    @Resource
    IIoService ioService;

    /**
     * 用于渲染IO陈列页面
     *
     * @param instanceId 实例id
     * @return ModelAndModel
     */
    @RequestMapping("/ioData")
    public ModelAndView ioData(@SessionAttribute long instanceId) {
        ModelAndView modelAndView = new ModelAndView();
        List<Io> ioList = ioService.getList(instanceId);
        modelAndView.addObject("ioList", ioList);
        modelAndView.setViewName("ioManager");
        return modelAndView;
    }

    /**
     * 用于渲染添加入库记录页面
     *
     * @return ModelAndView
     */
    @RequestMapping("/addIoPage")
    public ModelAndView addIoPage(@SessionAttribute User user) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", user);
        modelAndView.setViewName("addIo");
        return modelAndView;
    }

    /**
     * 用于添加IO记录
     *
     * @param instanceId 实例id
     * @param io         IO实体
     * @return AjaxResponse
     * @throws CustomException 当输入数据不完整时抛出该异常
     */
    @PostMapping("add")
    @ResponseBody
    @Transactional
    public AjaxResponse add(@SessionAttribute long instanceId, Io io) throws CustomException {
        ioService.add(instanceId, io);
        return AjaxResponse.success();
    }
}
